package io.bytes;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import io.TestResourcesDirectory;

/**
 * 文件输入输出字节流的演示，用于传输二进制文件
 * 
 * @author fidel
 */
public class FileDemo {
    public static void main(String[] args) {
        File file = new File(TestResourcesDirectory.PATH + File.separator + "BytesFileDemo.txt");
        // try-with-resources
        try (OutputStream os = new FileOutputStream(file)) {
            String txt = "FileOutputStream extends from OutputStream";
            final int len = 16;
            byte[] arr = new byte[len];
            for (int i = 0; i < txt.length(); i++) {
                int mod = i % len;
                arr[mod] = (byte) txt.charAt(i);
                if (mod == len - 1 || i == txt.length() - 1) {
                    if (mod == len - 1) {
                        // 将数组中的所有字节写入流
                        os.write(arr);
                    } else {
                        // 将数量不足数组长度的剩余字节写入流
                        os.write(arr, 0, mod + 1);
                    }
                }
            }
            InputStream is = new FileInputStream(file);
            int aByte;
            /*
             * 当读取的下一个字节的数据不为-1时，
             * 说明未到达流的末尾，则执行循环体
             */
            while (-1 != (aByte = is.read())) {
                // 将读取的数值转化为ASCII码的对应字符
                char c = (char) aByte;
                System.out.print(c);
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
